package org.ivwsqii.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ConnectionWatcher implements Watcher {
    //设置超时时间
    private static final int SESSION_TIMEOUT = 5000;
    protected ZooKeeper zk;
    //设置闭锁，当计数器为零时，主线程继续运行
    private CountDownLatch connectedSignal=new CountDownLatch(1);
    public void connect(String host) throws KeeperException, InterruptedException, IOException {
        //创建链接
        zk = new ZooKeeper(host, SESSION_TIMEOUT, this);
        //主线程等待
        connectedSignal.await();
    }
    //Watcher中的接口，当Zk链接成功后，此方法别调用
    @Override
    public void process(WatchedEvent event) {
        if (event.getState() == Event.KeeperState.SyncConnected){
            connectedSignal.countDown();
        }
    }
    public void close() throws InterruptedException {
        zk.close();
    }
}
